import MiException, {miError} from "./exception";
import {env} from "../env/env";
import {getLoginToken, setLoginToken} from "../service/user";
import {showToast} from "./tool";

const wxAccount = wx.getAccountInfoSync()
const {appId} = wxAccount.miniProgram

let refreshTokenComplete = true
let requestQueues = []

export function request(options) {

    options = Object.assign({
        header:{
            Authorization: "Bearer " + getLoginToken(),
            appid: appId,
            'uni-platform': 'mp-weixin',
        },
        method:'POST',
        data:{},
    }, options)

    const urlBase = `${env.host}/uniapp`

    return new Promise(async (resolve, reject) => {

        wx.request({
            url: `${urlBase}${options.url}`,
            data: options.data,
            header:options.header,
            method:options.method,
            success: res => {
                if (res.header.Authorization){  // 更新令牌
                    const token = res.header.Authorization.slice(7)
                    setLoginToken(token)
                }

                if(res.statusCode < 400){
                    if (res.data.error == 0){
                        resolve(res.data)
                    }else{
                        showToast(res.data.msg)
                        if (res.data.error == 10001){
                            wx.navigateTo({
                                url:'/pages/login/index'
                            })
                        }
                        reject(res)
                    }

                }else{
                    showToast("请求接口错误")
                    reject(res)
                }
            },
            fail: res => {
                showToast("请求服务器失败")
                reject(res)
            }
        })
    });
}

export function simpleGet(url, data){
    return request({
        url,
        method:"GET",
        data,
    })
}

export function simplePost(url, data){
    return request({
        url,
        method: "POST",
        data,
    })
}

export function simplePatch(url, data){
    return request({
        url,
        method: "PATCH",
        data,
    })
}
